# -*- coding: utf-8 -*-
from __future__ import absolute_import

import sys, os
try:
    from PySide2.QtGui import *
    from PySide2.QtCore import *
    from PySide2.QtWidgets import *
except ImportError:
    pass

class saveModelDialog(QDialog):
    def __init__(self, parent = None):
        super(saveModelDialog, self).__init__(parent)

        # formatting
        self.setWindowTitle("save model")

        title = QLabel(self)
        title.setText("input model name")

        # validator
        regexp = QRegExp('[A-Za-z0-9_]+')
        validator = QRegExpValidator(regexp)

        # widgets
        self.input = QLineEdit()
        self.input.setValidator(validator)

        # OK and Cancel buttons
        self.buttons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)

        # signals
        self.input.textChanged.connect(self.check_input)
        self.input.textChanged.emit(self.input.text())

        # layout
        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.addWidget(title)
        self.mainLayout.addWidget(self.input)
        self.mainLayout.addWidget(self.buttons)

        self.buttons.accepted.connect(self.checkName)
        self.buttons.rejected.connect(self.reject)

        # self.buttons.setEnabled(False)
        self.input.setFocus()


    def check_input(self, *args, **kwargs):
        sender = self.sender()
        validator = sender.validator()
        state = validator.validate(sender.text(), 0)[0]

        if state == QValidator.Acceptable:
            color = '#c4df9b' # green
        elif state == QValidator.Intermediate:
            color = '#fff79a' # yellow
        else:
            color = '#f6989d' # red
        sender.setStyleSheet('QLineEdit { background-color: %s }' % color)

    # get current data from the dialog
    def getInput(self):
        return self.input.text()
    
    def checkName(self):
        path = "models/" + self.getInput()
        if os.path.exists(path) :
            self.input.setText('#_shape_model_exit_#')
        else:
            self.accept()
